// ==UserScript==
// @name           Waze
// @namespace      https://waze-papyrus-extended-tools.googlecode.com/svn/trunk/
// @include        https://www.waze.com/cartouche/*
// @include        https://www.waze.com/map-editor/*
// @match          https://www.waze.com/cartouche/*
// @match          https://www.waze.com/map-editor/*
// @include        https://world.waze.com/cartouche/*
// @include        https://world.waze.com/map-editor/*
// @match          https://world.waze.com/cartouche/*
// @match          https://world.waze.com/map-editor/*
// @version        1.2.2
// ==/UserScript==



var version = "1.2.2";

// Compatibility with google chrome web browser
// Thanks to bgodette and Tim1987
if(window.navigator.vendor.match(/Google/)) {
  console.log("Patching google chrome environment");

  unsafeWindow = (function() {
    var el = document.createElement('p');
    el.setAttribute('onclick', 'return window;');
    return el.onclick();
  })();

  GM_deleteValue = function(name) {
    localStorage.removeItem(name);
  };

  GM_getValue = function(name, defaultValue) {
    var value = localStorage.getItem(name);
    if (!value) return defaultValue;
    var type = value[0];
    value = value.substring(1);
    switch (type) {
      case 'b': return value == 'true';
      case 'n': return Number(value);
      default: return value;
    }
  };

  GM_setValue = function(name, value) {
    localStorage.setItem(name, (typeof value)[0] + value);
  };
};

var $   = unsafeWindow.$;
var doc = unsafeWindow.document;
var wm  = unsafeWindow.wazeModel;
Array = unsafeWindow.Array; // Because unsafeWindow.Array have some extra prototype (like first())

function createElement(p, type, className) {
  var e = doc.createElement(type);
  if(p) p.appendChild(e);
  if (className != undefined) e.className = className;
  return e;
}

function createTextNode(p, txt) {
  p.appendChild(doc.createTextNode(txt));
  return p;
}



function getStreet(seg) {
  var sid = seg.attributes.primaryStreetID;
  if(sid) return wm.streets.objects[sid];
}

function getCity(str) {
  var cityId = str.cityID;
  if(cityId) return wm.cities.objects[cityId];
}

function getState(city) {
  var stateId = city.stateID;
  if (stateId) return wm.states.objects[stateId];
}

function getCountry(city) {
  var countryId = city.countryID;
  if(countryId) return wm.countries.objects[countryId];
}

function computeDicCountry() {
  var dicCountry = {};
  
  for(var segId in wm.segments.objects) {
    var seg = wm.segments.objects[segId];
    if(seg) {
      var str = getStreet(seg);
      var countryName = "";
      var stateName = "";
      var cityName = "";
      var strName = "";
      if(str) {
        if(str.name) strName = str.name;
        var city = getCity(str);
        if(city) {
          if(city.name) cityName = city.name;
          var country = getCountry(city);
          if(country && country.name) countryName = country.name;
          var state = getState(city);
          if (state && state.name) stateName = state.name;
        }
      }

      if(countryName == "Belgium") countryName = "BE";
      if(countryName == "Canada") countryName = "CAN";
      if(countryName == "France") countryName = "F";
      if(countryName == "Germany") countryName = "DE";
      if(countryName == "Mexico") countryName = "MEX";
      if(countryName == "Netherlands") countryName = "NL";
      if(countryName == "United States") countryName = "USA";
      
      
      var dicState = dicCountry[countryName];
      if (dicState == null) { dicState = {}; dicCountry[countryName] = dicState; }
      var dicCity = dicState[stateName];
      if(dicCity == null) { dicCity = {}; dicState[stateName] = dicCity; }
      var dicStr = dicCity[cityName];
      if(dicStr == null) { dicStr = {}; dicCity[cityName] = dicStr; }
      var lSeg = dicStr[strName];
      if(lSeg == null) { lSeg = new Array(); dicStr[strName] = lSeg; }
      lSeg.push(seg);
    }
  }  
  return dicCountry;
}

function refreshTable(tab, tbody) {
  console.log("Refresh");
  wm  = unsafeWindow.wazeModel;
  var dicCountry  = computeDicCountry();
  $(tbody).empty();
  for(var countryName in dicCountry) {
    var dicState = dicCountry[countryName];
    for(var stateName in dicState) {
      var dicCity = dicState[stateName];
      for(var cityName in dicCity) {
        var dicStr = dicCity[cityName];
        for(var strName in dicStr) {
          var lSeg = dicStr[strName]; 
          var tr = createElement(tbody, "TR");
          var td = createElement(tr, "TD");
          createTextNode(td, countryName);
          var td = createElement(tr, "TD");
        if(location.hostname == "www.waze.com") {
            createTextNode(td, stateName);
            var td = createElement(tr, "TD");
        }
          createTextNode(td, cityName);
          var td = createElement(tr, "TD");
          createTextNode(td, strName);
          var td = createElement(tr, "TD");
          
          var but = createElement(td, "INPUT");
          but.type = "button";
          but.value = lSeg.length;
          but.addEventListener("click", (function(lSeg) {
            return function(e) {
              unsafeWindow.selectionManager.select(lSeg);
            }; })(lSeg));
        }
      }
    }
  }
  $(tab).find("TD").css({borderWidth: "1px", borderStyle: "solid", padding: "2px"});
}

$(doc).ready(function() {
  console.log("Ready");
  window.setTimeout(function() {
    console.log("Timeout");
    $("#map-problems-explanation").remove();
    
    var user = $("#user-details");
    var para = createElement(null, "P");
    user.append(para);
    
    var divver = createElement(para, "DIV");
    $(divver).css( { fontSize: "10px", textAlign: "right" } );
    createTextNode(divver, "Extended tools V" + version);
    
    var but = createElement(para, "INPUT");
    but.type = "button";
    but.value = "Refresh table";
    but.addEventListener("click", function(e) { refreshTable(tab, tbody); });
    
    var log = createElement(para, "SPAN");
    $(log).css("font-size", "10px");
    
    var scrol = createElement(para, "DIV");
    $(scrol).css({ height: "670px", overflow: "auto" });
    
    var tab = createElement(scrol, "TABLE");
    $(tab).css("font-size", "10px");
    
    var thead = createElement(tab, "THEAD");
    $(thead).css( { fontSize: "12px", fontWeight: "bold" } );
    var td = createElement(thead, "TD");
    createTextNode(td, "Ctry");
    if(location.hostname == "www.waze.com") {
     var td = createElement(thead, "TD");
      createTextNode(td, "State");
   }
    var td = createElement(thead, "TD");
    createTextNode(td, "City");
    var td = createElement(thead, "TD");
    createTextNode(td, "Street");
    var td = createElement(thead, "TD");
    createTextNode(td, "Select");
    
    
    var tbody = createElement(tab, "TBODY");
    
    refreshTable(tab, tbody);
    
  }, 5000);
});
